import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:safety_platform/models/hidden_danger.dart';
import 'package:safety_platform/models/rectify_step.dart';
import 'package:safety_platform/models/situation.dart';
import 'package:safety_platform/utils.dart' show formatDate;
import 'package:safety_platform/components/button.dart';
import 'package:safety_platform/components/attachment.dart' show AttachmentPreviewGallery;
import 'package:safety_platform/components/hidden_danger.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:safety_platform/pages/services.dart';
import 'package:safety_platform/theme.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/services.dart';
class HiddenDangerRectifyPage extends StatefulWidget {
  final HiddenDanger hiddenDanger;

  const HiddenDangerRectifyPage({this.hiddenDanger});

  @override
  State<StatefulWidget> createState() => _HiddenDangerRectifyPageState();
}

class _HiddenDangerRectifyPageState extends State<HiddenDangerRectifyPage> {
  bool _selected = false;
  DateTime _reformDate;
  TextEditingController _controller;
  bool _submitting = false;
  HiddenDanger _hiddenDanger;

  String  _budget  = '0';

  SlidableController _slidableController;

  List<RectifyStep> _rectifySteps;
  @override
  void initState() {
    this._hiddenDanger = widget.hiddenDanger;
    _rectifySteps = List();
    _controller = TextEditingController();
    _slidableController = SlidableController();
    super.initState();
  }

  _buildRow(String title, String value) {
    if (value == null || value == 'null') {
      value = '';
    }
    return Container(
      padding: EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(255, 241, 241, 241),
          ),
        ),
      ),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(title),
          ),
          Expanded(
            flex: 2,
            child: Text(
              value,
              textAlign: TextAlign.right,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.grey),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // resizeToAvoidBottomPadding: false,
      // floatingActionButton: new FloatingActionButton(
      //   foregroundColor: Colors.white,
      //   elevation: 10.0,
      //   onPressed: () {},
      //   tooltip: '查看隐患',
      //   child: new Icon(Icons.add),
      // ),
      appBar: AppBar(
        title: new Text("添加整改信息"),
        elevation: 0,

        //     leading: appLeading(context),
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      body: SingleChildScrollView(
        child: Container(child: _body(context)),
      ),
      bottomNavigationBar: _bottomVavigationBar(),
    );
  }

  _submit() {
    setState(() {
      _submitting = true;
    });

    submitHiddenDangerRectification(this._hiddenDanger.id, this._selected,
            this._reformDate, this._budget)
        .then((HiddenDanger hd) {
      Fluttertoast.showToast(msg: '提交成功');

      Navigator.of(context).pop(hd);
      setState(() {
        _submitting = false;
      });
    }).catchError((error) {
      print('提交整改信息失败 $error');
      setState(() {
        _submitting = false;
      });
    });
  }


  _bottomVavigationBar() {
    // if (_task != null && _task.status == 'pending') {
    return Container(
        width: MediaQuery.of(context).size.width,
        height: 48,
        color: Colors.white,
        child: Button(
          loading: _submitting,
          buttonColor: Colors.white,
          onPressed: () {
            _submit();
            // Navigator.of(context).push(MaterialPageRoute(
            //     builder: (_) =>
            //         HiddenDangerRectifyPage(hiddenDanger: hiddenDanger)));
          },
          text: '提交',
          textSize: 18,
          textColor: Color.fromARGB(255, 27, 130, 210),
        )
      
        );
    // }
  }

  _onChanged(bool selected) {
    // setState(() {
    //   _selected = selected;
    // });
    if (selected) {
     
      DatePicker.showDatePicker(context,
          showTitleActions: true,
          minTime: DateTime.now().subtract(Duration(days: 1)),
          maxTime: DateTime.now().add(Duration(days: 365)), onChanged: (date) {
        print('change $date');
      }, onConfirm: (date) {
        print('confirm $date');
        // _reformDate = date;
        setState(() {
          _reformDate = date;
          _selected = true;
        });
      }, currentTime: DateTime.now(), locale: LocaleType.zh);
    } else {
      setState(() {
        _reformDate = null;
        _selected = false;
      });
    }
  }


  _rectifyDateWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(255, 241, 241, 241),
          ),
        ),
      ),
      // color: Colors.white,
      // margin: EdgeInsets.only(top: 8),
      child: Column(children: <Widget>[
        DecoratedBox(
          decoration: BoxDecoration(
            border: Border(bottom: BorderSide(

              width: 0.5,
              color: Color.fromARGB(255, 241, 241, 241),
            ),),
          ),
          child:SwitchListTile(
          value: _selected,
          // selected: _selected,

          onChanged: (selected) => _onChanged(selected),
          // secondary: Text('secondary'),
          title: Text(
            '限期整改',
            style: TextStyle(
              fontSize: 14,
              color: Colors.black,
            ),
          ),
          subtitle: _reformDate == null
              ? null
              : Text(formatDate(_reformDate, format: 'yyyy-MM-dd')),
        ),),
        DecoratedBox(
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          child: Container(
            padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: Row(
              children: <Widget>[
                Expanded(flex: 2, child: Text('预算金额')),
                Expanded(
                    flex: 1,
                    child: TextField(
                      onSubmitted: (budget) => setState(() {_budget =budget;}),
                      textAlign: TextAlign.right,
                      // maxLength: 10,
                      textInputAction: TextInputAction.done,
                      keyboardType: TextInputType.numberWithOptions(decimal: true),
                      inputFormatters: [
                        WhitelistingTextInputFormatter.digitsOnly,
                      ],
                      // inputFormatters: [.],
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: 0.toString(),
                        // suffixText: '元'
                      ),
                    )),
                Padding(child: Text('元'), padding: EdgeInsets.only(left: 8)),
              ],
            ),
          ),
          // trailing: SizedBox(
          //   child: TextField(),
          //   width: 80,
          //   height: 80,
          // ),
        ),
      ]),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    // _slidableController.dispose();
    super.dispose();
  }

  Widget _situationWidget() {
    List<Situation> situations = this._hiddenDanger.situations;

    if (situations == null) {
      situations = [];
    }
    int index = 0;
    List<Widget> children = situations.map((situation) {
      ++index;
      return ListTile(
        title: Text('$index. ${situation.content}'),
      );
    }).toList();
    return Container(
        margin: EdgeInsets.only(bottom: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            backgroundTitle('存在的问题'),
            DecoratedBox(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children:
                    ListTile.divideTiles(tiles: children, context: context)
                        .toList(),
              ),
              decoration: BoxDecoration(
                color: Colors.white,
              ),
            ),
             AttachmentPreviewGallery(
                attachments: _hiddenDanger.situationImages,
                collapseLabel: '查看问题图片',
              )
          ],
        ));
  }

  Widget _hiddenDangerDetail() {
    return Container(
        // margin: EdgeInsets.only(bottom: 8.0),
        child: Column(
      children: <Widget>[
        _buildRow('隐患部位', _hiddenDanger.risk.name),
        _buildRow('隐患类型', _hiddenDanger.classification.name),
        _buildRow('隐患级别', hiddenDangerGradeCodeToText(_hiddenDanger.grade)),
        Row(children: <Widget>[
          Expanded(
            child: Container(
              padding: EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  bottom: BorderSide(
                    width: 0.5,
                    color: Color.fromARGB(255, 241, 241, 241),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Text('隐患描述'),
                  Padding(
                    child: Text(
                      '${_hiddenDanger.memo}',
                      textAlign: TextAlign.left,
                      // overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.grey),
                    ),
                    padding: EdgeInsets.only(top: 4),
                  ),
                ],
              ),
            ),
          ),
        ])
      ],
    ));
  }

  Widget _body(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          // _hiddenDangerDetail(),
          HiddenDangerLiteWidget(_hiddenDanger),
          _situationWidget(),

          _rectifyDateWidget(),
          // _rectifyStepsWidget(),
        ],
      ),
    );
  }
}
